package uk.co.deanwild.materialshowcaseview;


import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

public class PrefsManager {
    // 从未开始
    public static final int SEQUENCE_NEVER_STARTED = 0;

    // 已经完成了
    public static final int SEQUENCE_FINISHED = -1;

    // 存储文件名
    private static final String PREFS_NAME = "material_showcaseview_prefs";

    // key前缀
    private static final String STATUS = "status_";

    // key后缀
    private String showcaseID;

    // 数据库操作的辅助类
    DatabaseHelper databaseHelper;

    // 本地存储
    Preferences preferences;

    public static PrefsManager getInstance() {
        return PrefsManagerInstance.INSTANCE;
    }

    private static class PrefsManagerInstance {
        private static final PrefsManager INSTANCE = new PrefsManager();
    }

    public void init(Context context) {
        databaseHelper = new DatabaseHelper(context);
        preferences = databaseHelper.getPreferences(PREFS_NAME);
    }

    public boolean isFinished() {
        int status = getSequenceStatus();
        return (status == SEQUENCE_FINISHED);
    }

    public void setFinished() {
        setSequenceStatus(SEQUENCE_FINISHED);
    }

    public void setShowcaseID(String showcaseID) {
        this.showcaseID = showcaseID;
    }

    public int getSequenceStatus() {
        captureException();
        return preferences.getInt(STATUS + showcaseID, SEQUENCE_NEVER_STARTED);
    }

    public void setSequenceStatus(int status) {
        captureException();
        preferences.putInt(STATUS + showcaseID, status).flush();
    }

    public void resetShowcase() {
        captureException();
        preferences.putInt(STATUS + showcaseID, SEQUENCE_NEVER_STARTED).flush();
    }

    public void resetAll() {
        captureException();
        preferences.clear().flush();
    }

    private void captureException(){
        if(preferences == null){
            throw new IllegalStateException("MyApplication no calling method: PrefsManager.init()");
        }
    }
}
